import React, {useEffect, useState} from 'react';

export default function StateDemo() {

  const [count, setCount] = useState(0);
  const [name, setName] = useState('White');

  function add() {
    setCount(count + 1); // 第一种写法：对值直接操作
    setCount(count => count + 1); // 第二种写法，回调函数
    console.log('setCount', count)

    // 宏任务 直接打印
    setTimeout(() => {
      setCount(count + 4);
      console.log('setTimeout', count)
    }, 0)

    // 微任务 直接打印
    Promise.resolve().then(res => {
      setCount(count + 5);
      console.log('Promise', count)
    })
  }

  const changeName = () => {
    setName('jack')
  }

  useEffect(() => {
    console.log('LearnReactuseState', count)
  }, [count])

  /**
   *
   * 很有意思
   * 当点击按钮“点我 + 1”的时候, 输出依次是
   * setCount 0
   * LearnReactuseState.jsx:31 LearnReactuseState 2
   * LearnReactuseState.jsx:22 Promise 0
   * LearnReactuseState.jsx:31 LearnReactuseState 5
   * LearnReactuseState.jsx:16 setTimeout 0
   * LearnReactuseState.jsx:31 LearnReactuseState 4
   *
   * 事实证明，两次setCount会合并执行
   * 一次Promise先执行，根据初始值去计算
   * 一次setTimout最后执行，并修改最终值
   * */

  return (
    <div>
      {/*使用变量*/}
      <h2>当前求和为：{count}</h2>
      <button onClick={add}> 点我+1</button>
      <br/>
      <h2>我的名字是：{name}</h2>
      <button onClick={changeName}>点我改名</button>
    </div>
  )
}
